package com.sl.utils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.util.StringUtils;

public class DataConverter {

	public static Date toDate(String sdate) {
		String[] pattern = new String[] { "yyyy-MM", "yyyyMM", "yyyy/MM", "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd",
				"yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm","yyyy/MM/dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS",
				"yyyy/MM/dd HH:mm:ss.SSS" };
		Date ddate = null;
		if (!StringUtils.hasText(sdate))
			return null;
		try {
			ddate = DateUtils.parseDate(sdate, pattern);
		} catch (ParseException ex) {
			System.out.println("com.cisdi.gae.util.toDate:conversion failure!" + ex.getMessage());
		}
		return ddate;
	}

	/**返回当前或给定日期的日间序号:
	 * @param param
	 * @return
	 */
	public static String toTimeCode(Date... param) {
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		if (param.length>0)
			date = param[0];
		return format.format(date);

	}

	public static Date formatDateYMD(String s1) {

		DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
		if (null != s1)
			try {
				return format.parse(s1.toString());
			} catch (ParseException e) {
				e.printStackTrace();
			}
		return null;
	}

	public static String toYMDMS(Date date) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (null != date)
			return format.format(date);

		return null;
	}

	public static String toDateYMD(Date date) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
		if (null != date)
			return format.format(date);

		return null;
	}
	public static String toZnDateYMD(Date date) {
		DateFormat format = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
		if (null != date)
			return format.format(date);

		return null;
	}
	public static Date toStartDate(Date date) {
		if (null != date) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			return cal.getTime();
		}
		return null;
	}

    ///获得当月的第一天的凌晨0点
	public static Date toMonthStartDate(Date date){
		if (null != date) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.MONTH, 0);
			cal.set(Calendar.DAY_OF_MONTH,1);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			return cal.getTime();
		}
		return null;
	}
	public static Date toEndDate(Date date) {
		if (null != date) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(Calendar.HOUR_OF_DAY, 23);
			cal.set(Calendar.MINUTE, 59);
			cal.set(Calendar.SECOND, 59);
			cal.set(Calendar.MILLISECOND, 250);
			return cal.getTime();
		}
		return null;
	}

	/**
	 * 获取年份；
	 */
	public static String getYear(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String printDate = sdf.format(d);
		String[] date = printDate.split("-");
		String year = date[0];
		// String month = date[1];
		// String day = date[2];
		return year;
	}

	/**
	 * 获取月份；
	 */
	public static String getMonth(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String printDate = sdf.format(d);
		String[] date = printDate.split("-");
		// String year = date[0];
		String month = date[1];
		// String day = date[2];
		return month;
	}

	/**
	 * 获取月份；
	 */
	public static String getDay(Date d) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String printDate = sdf.format(d);
		String[] date = printDate.split("-");
		// String year = date[0];
		// String month = date[1];
		String day = date[2];
		return day;
	}

	/**
	 * 两个时间相差距离多少天多少小时多少分多少秒
	 * 
	 * @param str1
	 *            时间参数 1 格式：1990-01-01 12:00:00
	 * @param str2
	 *            时间参数 2 格式：2009-01-01 12:00:00
	 * @return String 返回值为：xx天xx小时xx分xx秒
	 */
	public static String getDistanceTime(Date date1, Date date2) {
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		try {
			long time1 = date1.getTime();
			long time2 = date2.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (day == 0 && hour == 0 && min == 0 || sec == 0) {
			if (day != 0 && hour != 0 && min != 0) {
				return day + "天" + hour + "小时" + min + "分";
			} else if (hour != 0 && min != 0 && day == 0) {
				return hour + "小时" + min + "分";
			} else if (min != 0 && hour == 0 && day == 0) {
				return min + "分";
			} else if (day != 0 && hour == 0 && min == 0) {
				return day + "天";
			} else if (hour != 0 && day == 0 && min == 0) {
				return hour + "小时";
			} else {
				return sec + "秒";
			}
		} else if (day == 0 && hour == 0) {
			return min + "分" + sec + "秒";
		} else if (day == 0) {
			return hour + "小时" + min + "分" + sec + "秒";
		} else {
			return day + "天" + hour + "小时" + min + "分" + sec + "秒";
		}
	}

	/**
	 * 将数字格式的年、月、日转化为文字格式输出，如：2014年11月12日 --> 二零一四年十一月十二日；
	 */

	private static final String[] NUMBERS = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };

	public static String toChinese(String str) {
		StringBuffer sb = new StringBuffer();
		sb.append(getSplitDateStr(str, 0)).append("年").append(getSplitDateStr(str, 1)).append("月")
				.append(getSplitDateStr(str, 2)).append("日");
		return sb.toString();
	}

	private static String getSplitDateStr(String str, int unit) {
		// unit是单位 0=年 1=月 2日
		String[] DateStr = str.split("-");
		if (unit > DateStr.length)
			unit = 0;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < DateStr[unit].length(); i++) {

			if ((unit == 1 || unit == 2) && Integer.valueOf(DateStr[unit]) > 9) {
				sb.append(convertNum(DateStr[unit].substring(0, 1))).append("十")
						.append(convertNum(DateStr[unit].substring(1, 2)));
				break;
			} else {
				sb.append(convertNum(DateStr[unit].substring(i, i + 1)));
			}
		}
		if (unit == 1 || unit == 2) {
			return sb.toString().replaceAll("^一", "").replace("零", "");
		}
		return sb.toString();
	}

	private static String convertNum(String str) {
		return NUMBERS[Integer.valueOf(str)];
	}

	/**
	 * 采用分段的方式将给定小写金额转换成中文大写形式 从小数点开始向前数，四位为一段 支持整数位最多13位、小数位最多2位，多于两位的小数会被忽略
	 * 
	 * @param value
	 *            小写金额
	 * @return 转换后的中文大写字符串
	 */
	public static String toBigMode(double value) {
		final char[] NUMBER_CHAR = "零壹贰叁肆伍陆柒捌玖".toCharArray(); // 大写数字
		final String[] IN_UNIT_CHAR = { "", "拾", "佰", "仟" }; // 段内字符
		final String[] UNIT_NAME = { "", "万", "亿", "万亿" }; // 段名

		// long longValue = new Double(value * 100).longValue(); // 转换成整数
		// System.out.println(longValue);
		String valStr = new BigDecimal(Math.ceil(value * 100)).toString(); // 转换成字符串

		StringBuffer prefix = new StringBuffer(); // 整数部分转化的结果
		StringBuffer suffix = new StringBuffer(); // 小数部分转化的结果

		if (valStr.length() <= 2) // 只有小数部分
		{
			prefix.append("零元");
			if (valStr.equals("0")) {
				suffix.append("零角零分");
			} else if (valStr.length() == 1) {
				suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("分");
			} else {
				suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("角");
				suffix.append(NUMBER_CHAR[valStr.charAt(1) - '0']).append("分");
			}
		} else {
			int flag = valStr.length() - 2;
			String head = valStr.substring(0, flag); // 取整数部分
			String rail = valStr.substring(flag); // 取小数部分

			if (head.length() > 13) {
				return "数值太大(最大支持13位整数)，无法处理。";
			}

			// 处理整数位
			char[] ch = head.toCharArray();
			int zeroNum = 0; // 连续零的个数
			for (int i = 0; i < ch.length; i++) {
				int index = (ch.length - i - 1) % 4; // 取段内位置，介于 3 2 1 0
				int indexLoc = (ch.length - i - 1) / 4; // 取段位置，介于 3 2 1 0

				if (ch[i] == '0') {
					zeroNum++;
				} else {
					if (zeroNum != 0) {
						if (index != 3) {
							prefix.append("零");
						}
						zeroNum = 0;
					}
					prefix.append(NUMBER_CHAR[ch[i] - '0']); // 转换该位置的数

					prefix.append(IN_UNIT_CHAR[index]); // 添加段内标识
				}

				if (index == 0 && zeroNum < 4) // 添加段名
				{
					prefix.append(UNIT_NAME[indexLoc]);
				}
			}
			prefix.append("元");

			// 处理小数位
			if (rail.equals("00")) {
				suffix.append("整");
			} else if (rail.startsWith("0")) {
				suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("分");
			} else {
				suffix.append(NUMBER_CHAR[rail.charAt(0) - '0']).append("角");
				suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("分");
			}
		}

		return prefix.append(suffix).toString();
	}

	/**
	 * 
	 * 将数字转换为中文大写字符串
	 * 
	 * 
	 */
	public static String toBig(double value) {
		final char[] NUMBER_CHAR = "零壹贰叁肆伍陆柒捌玖".toCharArray(); // 大写数字
		final String[] IN_UNIT_CHAR = { "", "拾", "佰", "仟" }; // 段内字符
		final String[] UNIT_NAME = { "", "万", "亿", "万亿" }; // 段名
		String valStr = new BigDecimal(Math.ceil(value * 100)).toString(); // 转换成字符串

		StringBuffer prefix = new StringBuffer(); // 整数部分转化的结果
		StringBuffer suffix = new StringBuffer(); // 小数部分转化的结果

		if (valStr.length() <= 2) // 只有小数部分
		{
			prefix.append("");
			if (valStr.equals("0")) {
				suffix.append("");
			} else if (valStr.length() == 1) {
				suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("");
			} else {
				suffix.append(NUMBER_CHAR[valStr.charAt(0) - '0']).append("");
				suffix.append(NUMBER_CHAR[valStr.charAt(1) - '0']).append("");
			}
		} else {
			int flag = valStr.length() - 2;
			String head = valStr.substring(0, flag); // 取整数部分
			String rail = valStr.substring(flag); // 取小数部分

			if (head.length() > 13) {
				return "数值太大(最大支持13位整数)，无法处理。";
			}

			// 处理整数位
			char[] ch = head.toCharArray();
			int zeroNum = 0; // 连续零的个数
			for (int i = 0; i < ch.length; i++) {
				int index = (ch.length - i - 1) % 4; // 取段内位置，介于 3 2 1 0
				int indexLoc = (ch.length - i - 1) / 4; // 取段位置，介于 3 2 1 0

				if (ch[i] == '0') {
					zeroNum++;
				} else {
					if (zeroNum != 0) {
						if (index != 3) {
							prefix.append("零");
						}
						zeroNum = 0;
					}
					prefix.append(NUMBER_CHAR[ch[i] - '0']); // 转换该位置的数

					prefix.append(IN_UNIT_CHAR[index]); // 添加段内标识
				}

				if (index == 0 && zeroNum < 4) // 添加段名
				{
					prefix.append(UNIT_NAME[indexLoc]);
				}
			}
			prefix.append("");

			// 处理小数位
			if (rail.equals("00")) {
				suffix.append("");
			} else if (rail.startsWith("0")) {
				suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("");
			} else {
				suffix.append(NUMBER_CHAR[rail.charAt(0) - '0']).append("");
				suffix.append(NUMBER_CHAR[rail.charAt(1) - '0']).append("");
			}
		}

		return prefix.append(suffix).toString();
	}
/**返回指定分隔符最后一段，通常用于得到文件路径中的扩展名
 * @param source
 * @param splitter
 * @return
 */
public static String getLastSplitPart(String source,String splitter){
	String lastPart="";
	if(null!=source && source.length()>0){
		int from=source.lastIndexOf(splitter);
		if(from<0) return "";
		lastPart=source.substring(from+1, source.length());
	}
	
	return lastPart;
};
}
